﻿@page "/register"
@rendermode InteractiveAuto
@inject NavigationManager nav

<h3>Register</h3>

<p>@message</p>
<p><a href="/login">@login</a></p>

<EditForm Model="reg" OnValidSubmit="OnValid" style="max-width:500px;">
	<DataAnnotationsValidator />
	<ValidationSummary />
	<div class="mb-2">
		<InputText class="form-control" @bind-Value="reg.email" placeholder="Enter Email"></InputText>
	</div>
	<div class="mb-2">
		<InputText type="password" class="form-control" @bind-Value="reg.password" placeholder="Enter Password"></InputText>
	</div>
	<div class="mb-2">
		<InputText type="password" class="form-control" @bind-Value="reg.confirmpwd" placeholder="Confirm Password"></InputText>
	</div>
	<div class="mb-2 text-right">
		<button class="btn btn-secondary" disabled="@isDisabled">register</button>
	</div>
</EditForm>

@code {

	RegModel reg = new RegModel();
	string message = string.Empty, login = string.Empty;
	bool isDisabled = false;

	private async Task OnValid()
	{
		isDisabled = true;
		using(var Http = new HttpClient { BaseAddress = new Uri(nav.BaseUri) })
		{
			using (var msg = await System.Net.Http.Json.HttpClientJsonExtensions.PostAsJsonAsync<RegModel>(Http, "/api/auth/register", reg, System.Threading.CancellationToken.None))
			{
				if (msg.IsSuccessStatusCode)
				{
					LoginResult result = await msg.Content.ReadFromJsonAsync<LoginResult>();
					message = result.message;
					if (result.success)
					{
						message += " Please LOGIN to continue.";
						login = "Click here to LOGIN.";
					}
					else
						isDisabled = false;
				}
			}
		}
	}
}